# coding:utf8
import os
import re
import time
import sys
from ruamel import yaml

def get_apps(apps_path):
    apps = {}
    with open(apps_path) as f:
        for l in f.readlines():
            l = l.strip()
            if l and not l.find('#') == 0:
                app, port = l.split(':')
                apps[app] = port
    return apps


def write_file(file_path, content):
    with open(file_path, 'w') as f:
        f.write(content)


def read_file(file_path):
    with open(file_path) as f:
        return f.read()


def gen_dir(catalog_parent_path, version, chart, questions, values):
    app_dir_path = os.path.join(catalog_parent_path, version)
    template_path = os.path.join(app_dir_path, 'templates')
    if not os.path.exists(app_dir_path):
        os.makedirs(template_path)
    chart = chart % version
    chart_file = os.path.join(app_dir_path, "Chart.yaml")
    questions_file = os.path.join(app_dir_path, "questions.yaml")
    values_file = os.path.join(app_dir_path, "values.yaml")
    write_file(chart_file, chart)
    write_file(questions_file, questions)
    write_file(values_file, values)
    return template_path


def gen_deployment(apps, plan_file, outdir, modules_template_path):
    tpl_file = os.path.join(modules_template_path, 'catalog-tpl')
    tpl_file1 = os.path.join(modules_template_path, 'catalog-tpl1')
    tpl = read_file(tpl_file)
    tpl1 = read_file(tpl_file1)
    java_ops = '-Xms256m -Xmx512m'
    java_ops0 = '-Xms1024m -Xmx1024m'
    java_ops1 = '-Xms512m -Xmx1024m'
    print "start 88"
    print apps
    with open(plan_file) as f:
        lines = f.readlines()
        for s in lines:
            l = s.strip()
            if l and not l.find('#') == 0:
                name, branch = l.split("=")
                name = name.strip()
                branch = branch.strip()
                container_port = apps.get(name)
                print "=======start for"
                print apps
                if not container_port:
                  continue
                dubbo_container_port = '{}'.format(int(container_port) - int('1'+''.join(['0']*(len(container_port)-1))))
                print name, container_port,dubbo_container_port, branch
                if name in ['gmcf-gwc','gmcf-lmc','gmcf-cmc','gmcf-lsc']:
                    java_ops = java_ops0
                elif name in ['gmcf-ecc','gmcf-umf']:
                    java_ops = java_ops1
                td = {
                    "name": name,
                    "container_port": container_port,
                    "host_port": container_port,
                    "branch": branch,
                    "java_ops": java_ops
                }
                if name in ['gmcf-ocg']:
                    td["dubbo_container_port"] = dubbo_container_port
                    c = tpl1 % td
                else:
                    c = tpl % td
                print "name3"
                print name
                write_file(os.path.join(outdir, "%s.yaml" % name), c)

def init(catalog_git_path,git_url):
    os.system('rm -rf %s' % catalog_git_path)
    os.system('mkdir -p %s' % catalog_git_path)
    res = os.popen('cd %s && git clone %s .' % (catalog_git_path,git_url))
    print res.read()
    time.sleep(2)

def push(git_dir, version):
    print '【git push】'
    res = os.popen('cd %s && git add . && git commit -am "init %s"' % (git_dir,version))
    print res.read()
    res = os.popen('cd %s && git push origin master' % git_dir)
    print res.read()
    #pass


def gen_modules(catalog_git_path,modules_template_path,plan_path,plan_name,apps):
    print '【生成yml】'
    app_parent_path = os.path.join(catalog_git_path, 'liwen-application')
    plan_file = os.path.join(plan_path, plan_name)
    print "=============plan_file"
    print plan_file
    chart_file = os.path.join(modules_template_path,'Chart')
    questions_file = os.path.join(modules_template_path,'questions')
    values_file = os.path.join(modules_template_path,'values')
    configmap_file = os.path.join(modules_template_path,'configmap')

    version = re.findall('[\d\.]+', plan_name)[0]
    chart = read_file(chart_file)
    questions = read_file(questions_file)
    values = read_file(values_file)
    deployment_outdir = gen_dir(app_parent_path, version, chart, questions, values)
    if deployment_outdir:
        write_file(os.path.join(deployment_outdir, 'configmap.yaml'), read_file(configmap_file))
        gen_deployment(apps, plan_file, deployment_outdir,modules_template_path)


def gen_midware(catalog_git_path,modules_template_path,plan_name):
    pass

def update_midware_version(plan_path,catalog_git_path):
    mdict = None
    request_yaml= os.path.join(catalog_git_path,'liwen-midware','questions.yml')
    vs = os.listdir(plan_path)
    vs = filter(None, [re.findall('[\d.]+', v) and v or None for v in vs])
    vs = sorted(vs, cmp=lambda x, y: re.findall('\d{8}', x)[0] < re.findall('\d{8}', y)[0] or -1)
    tags = vs[:5]
    tags = ['config_v%s' % '_'.join(re.findall('[\d.]+',v)) for v in tags]
    with open(request_yaml) as f:
        yml = yaml.load(f.read(), Loader=yaml.RoundTripLoader)
        variables = yml.get('questions')
        for v in variables:
            if v['variable'] == 'template.IMAGE_TAGNAME':
                v['options'] = tags
                mdict = yml
                break
    with open(request_yaml, 'w') as f:
        mdict and yaml.dump(mdict, f, Dumper=yaml.RoundTripDumper)

if __name__ == "__main__":
    git_url = "https://gitee.com/xiaoliwen/lw-rancher-catelog.git"
    modules_template_path = os.path.join('template','module')
    # midware_template_path = os.path.join('template','midware')
    catalog_git_path = '../app-store'
    plan_path = os.environ['PlanPath']
    plan_name = os.environ['PlanName']
    # jenkins的apps重写入model中
    os.environ.get('apps') and write_file(os.path.join(modules_template_path,'apps'),os.environ.get('apps'))
    apps = get_apps(os.path.join(modules_template_path,'apps'))
    print "=============catalog_git_path"
    print catalog_git_path
    print "=============modules_template_path"
    print modules_template_path
    print "=============plan_path"
    print plan_path
    print "=============plan_name"
    print plan_name
    print "初始化cattalog============================================="
    init(catalog_git_path,git_url)
    gen_modules(catalog_git_path,modules_template_path,plan_path,plan_name,apps)
     # update_midware_version(plan_path,catalog_git_path)
    push(catalog_git_path, plan_name)